"""
主题上下文工具函数
提供全局获取启用主题的功能
"""
from functools import wraps
from flask import g, current_app
from apps.extensions import db
from apps.modules.admin.models.sys.sys_themes import Themes


def get_active_theme():
    """
    获取当前启用的主题数据
    
    Returns:
        dict: 主题数据字典，包含所有字段信息
        None: 如果没有启用的主题
    
    Example:
        theme = get_active_theme()
        if theme:
            print(f"当前主题: {theme['name']}")
            print(f"主题描述: {theme['description']}")
    """
    try:
        # 查询启用的主题
        theme = Themes.query.filter(Themes.active == 1).first()
        
        if theme:
            return {
                'id': theme.id,
                'name': theme.name,
                'screenshot': theme.screenshot,
                'description': theme.description,
                'author': theme.author,
                'author_and_uri': theme.author_and_uri,
                'version': theme.version,
                'active': theme.active,
                'has_update': theme.has_update,
                'update_uri': theme.update_uri,
                'create_time': theme.create_time,
                'update_time': theme.update_time
            }
        return None
    except Exception as e:
        current_app.logger.error(f"获取启用主题失败: {str(e)}")
        return None


def get_active_theme_cached():
    """
    获取当前启用的主题数据（带缓存）
    使用Flask的g对象进行请求级别的缓存
    
    Returns:
        dict: 主题数据字典
        None: 如果没有启用的主题
    """
    # 检查是否已经在g对象中缓存
    if hasattr(g, 'active_theme'):
        return g.active_theme
    
    # 获取主题数据
    theme_data = get_active_theme()
    
    # 缓存到g对象中
    g.active_theme = theme_data
    
    return theme_data


def get_active_theme_name():
    """
    获取当前启用主题的名称
    
    Returns:
        str: 主题名称
        None: 如果没有启用的主题
    """
    theme = get_active_theme_cached()
    return theme['name'] if theme else None


def get_active_theme_path():
    """
    获取当前启用主题的模板路径
    
    Returns:
        str: 主题模板路径
        None: 如果没有启用的主题
    """
    theme = get_active_theme_cached()
    if theme:
        return f"ppress/{theme['name']}"
    return None


def get_active_theme_info():
    """
    获取当前启用主题的基本信息
    
    Returns:
        dict: 包含name, description, author, version的基本信息
        None: 如果没有启用的主题
    """
    theme = get_active_theme_cached()
    if theme:
        return {
            'name': theme['name'],
            'description': theme['description'],
            'author': theme['author'],
            'version': theme['version']
        }
    return None


def require_active_theme(f):
    """
    装饰器：确保有启用的主题
    
    Args:
        f: 被装饰的函数
    
    Returns:
        装饰后的函数
    
    Example:
        @require_active_theme
        def my_view():
            theme = get_active_theme_cached()
            return render_template(f"{theme['name']}/index.html")
    """
    @wraps(f)
    def decorated_function(*args, **kwargs):
        theme = get_active_theme_cached()
        if not theme:
            # 可以根据需要返回错误页面或重定向
            return "没有启用的主题", 500
        return f(*args, **kwargs)
    return decorated_function


def theme_context_processor():
    """
    Flask上下文处理器
    自动在所有模板中提供主题信息
    
    Returns:
        dict: 包含主题信息的字典
    """
    theme = get_active_theme_cached()
    return {
        'active_theme': theme,
        'theme_name': theme['name'] if theme else None,
        'theme_path': f"ppress/{theme['name']}" if theme else None,
        'theme_info': get_active_theme_info()
    }


def get_theme_template_path(template_name):
    """
    获取主题模板的完整路径
    
    Args:
        template_name (str): 模板名称，如 'index.html'
    
    Returns:
        str: 完整的模板路径
        None: 如果没有启用的主题
    
    Example:
        template_path = get_theme_template_path('article.html')
        # 返回: 'ppress/my_theme/article.html'
    """
    theme = get_active_theme_cached()
    if theme:
        return f"ppress/{theme['name']}/{template_name}"
    return None


def get_theme_static_path(static_file):
    """
    获取主题静态文件的路径
    
    Args:
        static_file (str): 静态文件路径，如 'css/style.css'
    
    Returns:
        str: 静态文件URL路径
        None: 如果没有启用的主题
    
    Example:
        css_path = get_theme_static_path('css/style.css')
        # 返回: '/static/ppress/my_theme/css/style.css'
    """
    theme = get_active_theme_cached()
    if theme:
        return f"/static/ppress/{theme['name']}/{static_file}"
    return None


def is_theme_active(theme_name):
    """
    检查指定主题是否为当前启用主题
    
    Args:
        theme_name (str): 主题名称
    
    Returns:
        bool: 是否为当前启用主题
    """
    theme = get_active_theme_cached()
    return theme and theme['name'] == theme_name


def get_theme_config():
    """
    获取主题配置信息（用于前端使用）
    
    Returns:
        dict: 主题配置信息
        None: 如果没有启用的主题
    """
    theme = get_active_theme_cached()
    if theme:
        return {
            'name': theme['name'],
            'title': theme.get('description', theme['name']),
            'author': theme['author'],
            'version': theme['version'],
            'has_update': bool(theme['has_update']),
            'update_uri': theme['update_uri'],
            'screenshot': theme['screenshot']
        }
    return None


def clear_theme_cache():
    """
    清除主题缓存
    在主题状态变更后调用此函数
    """
    if hasattr(g, 'active_theme'):
        delattr(g, 'active_theme')


# 便捷函数别名
active_theme = get_active_theme_cached
theme_name = get_active_theme_name
theme_path = get_active_theme_path
theme_info = get_active_theme_info 